// 提供五套可选主题色
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
import './define.dart';

///log级别
enum ZFLogLevel {
  ///蓝牙扫描
  bleScan(1 << 0, 'blescan:'),

  ///回连
  reconnect(1 << 1, 'rec:'),

  ///网络请求
  net(1 << 2, 'net:'),

  ///蓝牙指令
  cmdBle(1 << 3, 'cmdble:'),

  ///Wifi指令
  cmdWifi(1 << 4, 'cmdwifi:'),

  ///数据来自Wifi
  dataFromWifi(1 << 5, 'fromwifi:');

  final int value;
  final String prefix;
  const ZFLogLevel(this.value, this.prefix);
}

const _themes = <MaterialColor>[
  Colors.blue,
  Colors.cyan,
  Colors.teal,
  Colors.green,
  Colors.red,
];

class Global {
  static late SharedPreferences _prefs;
  static SharedPreferences get prefs => _prefs;
  static Logger logger = Logger(
      printer:
          PrettyPrinter(methodCount: kReleaseMode ? 0 : 2, printTime: true),
      filter: kDevMode ? ProductionFilter() : DevelopmentFilter(),
      level: kDevMode ? Level.verbose : Level.error); //配置log分级输出

  // 可选的主题列表
  static List<MaterialColor> get themes => _themes;

  // 是否为release版
  static bool get isRelease => const bool.fromEnvironment("dart.vm.product");

  static bool isUserDevMode() {
    return prefs.getBool('_wh_user_dev_on') ?? false;
  }

  ///LogLevel级别
  static int logLevel = ZFLogLevel.bleScan.value |
      ZFLogLevel.reconnect.value |
      ZFLogLevel.cmdBle.value |
      ZFLogLevel.cmdWifi.value |
      ZFLogLevel.dataFromWifi.value |
      ZFLogLevel.net.value;
}

final logger = Global.logger;

///是否用户dev模式
bool get kUserDevMode => Global.isUserDevMode();

///日志打印
void zfLog(String msg,
    {String prefix = '', void Function(String msg)? onDone}) {
  if (prefix.startsWith(ZFLogLevel.reconnect.prefix)) {
    if (Global.logLevel & ZFLogLevel.reconnect.value == 0) {
      return;
    }
  }
  if (prefix.startsWith(ZFLogLevel.bleScan.prefix)) {
    if (Global.logLevel & ZFLogLevel.bleScan.value == 0) {
      return;
    }
  }

  if (prefix.startsWith(ZFLogLevel.cmdBle.prefix)) {
    if (Global.logLevel & ZFLogLevel.cmdBle.value == 0) {
      return;
    }
  }

  if (prefix.startsWith(ZFLogLevel.cmdWifi.prefix)) {
    if (Global.logLevel & ZFLogLevel.cmdWifi.value == 0) {
      return;
    }
  }

  if (prefix.startsWith(ZFLogLevel.net.prefix)) {
    if (Global.logLevel & ZFLogLevel.net.value == 0) {
      return;
    }
  }

  if (prefix.startsWith(ZFLogLevel.dataFromWifi.prefix)) {
    if (Global.logLevel & ZFLogLevel.dataFromWifi.value == 0) {
      return;
    }
  }

  msg = prefix + msg;
  onDone?.call(msg);
  logger.d(msg);
}
